package user;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import server.Connector;
import util.Message;
import businessLogicService.UserBLService;
import dataPO.UserPO;

public abstract class User implements UserBLService {
	
	protected final String ID;
	private static final String PREFIX = "user.";
	protected String password;
	protected UserPO accountInfo;
	
	public User(String ID, String password) {
		this.ID = ID;
		this.password = password;
		this.accountInfo = (UserPO) Connector.getAccountInfo(ID).getItem();
	}

	@Override
	public Message modifyPassword(String newPassword) {
		this.password = newPassword;
		this.accountInfo.setPassword(newPassword);
		return Connector.update(this.accountInfo);
	}

	@Override
	public Message searchCourse(String...content) {
	    return Connector.getCourseInfo(content);
	}

	@Override
	public Message showMyAccountInfo() {
		return Connector.getAccountInfo(this.ID);
	}

	@Override
	public Message showTeachFrameInfo() {
		return Connector.getTeachFrame();
	}

	@Override
	public Message showTeachPlan(String department) {
		return Connector.getTeachPlan(department);
	}
	
	public String getUserType() {
	    if(accountInfo == null) {
            return null;
        }
	    return this.accountInfo.getUserType();
	}
	
	public String getName() {
	    if(accountInfo == null) {
	        return null;
	    }
	    return this.accountInfo.getName();
	}
	
	public String getPassword() {
	    return this.password;
	}

	public static User login(String userID, String password) {
		UserPO item = (UserPO) ( Connector.getAccountInfo(userID).getItem() );
		if( password.equals( item.getPassword() ) ) {
			
		    String type = item.getUserType();

			try {
				Class<?> c = Class.forName( PREFIX + type );
				Constructor<?> cons = c.getConstructor(String.class, String.class);
				User user = (User) cons.newInstance(userID, password);
				return user;
			
			} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
			}		    
		}
		return null;
	}

}
